import Config from "@/libs/config";
import JSEncrypt from "jsencrypt/bin/jsencrypt.min";
import Util from "@/libs/framework/util"
import _ from "vue-upload-component";
let user = undefined;
let token = undefined;
let isLogin = false;
let resources = undefined;
let framework = undefined;
let initLogin = Config.setting.initLogin;
let miniappurl = {};
let results = {};
let list = [];
let homepage = undefined;
let nextRoute = undefined;
class Account {

  constructor(fw) {
    framework = fw;
    if (initLogin) {
      this.initLogin();
    }
  }

  next(r) {
    nextRoute = r;
  }

  initLogin() {
    //需要前置加载plus
    if (window.plus && plus.webview.currentWebview().miniapp) {
      this.miniLogin();
    } else {
      this.getUser().then(() => {
        if (token) {
          this.autoLogin();
        } else {
          this.ssoLogin();
        }
      });
    }
    /*this.getUser().then(() => {
      if (token) {
        this.autoLogin();
      } else {
        this.ssoLogin();
      }
    });*/
  }

  async getUser() {
    let u = await framework.db.users.orderBy("loginTime").desc().toArray();
    if (u && u.length > 0) {
      user = u[0].user;
      token = u[0].token;
      resources = u[0].resources;
      miniappurl.serverUrl = u[0].miniappurl
      if (vue && vue.$store) {
        vue.$store.commit("setResources", resources);
      }
    }
    return user;
  }

  setUser(user, token, resources, miniappurl) {
    isLogin = true;
    framework.db.users.put({
      loginId: user.loginId,
      user: user,
      token: token,
      resources: resources,
      loginTime: new Date(),
      miniappurl: miniappurl
    });
  }

  removeUser() {
    isLogin = false;
    token = undefined;
    if (user) {
      framework.db.users.delete(user.loginId);
    }
    user = undefined;
  }

  isLogin() {
    return isLogin && user != undefined && token != undefined;
  }

  login(params, callback, async) {
    let self = this;
    if (window.qmplus.isMobile()) {
      params.deviceId = window.qmplus.device.uuid;
      params.deviceName = window.qmplus.device.model;
      params.deviceVendor = window.qmplus.device.vendor;
      // params.deviceNetwork = window.qmplus.networkinfo.getCurrentType();
      params.osName = window.qmplus.os.name;
      params.osVendor = window.qmplus.os.vendor;
      params.osVersion = window.qmplus.os.version;
      params.osLanguage = window.qmplus.os.language;
      params.imei = window.qmplus.device.imei;
      // params.imsi = window.qmplus.device.imsi.join(",");
      params.marketChannel = window.qmplus.runtime.channel;
    } else if (window.qmplus.isElectron()) {
      let os = window.ipcRenderer.sendSync("getWindInfo");
      params.deviceId = os.deviceId;
      // TODO 无法获取设备名称
      params.deviceName = "Electron";
      params.deviceVendor = os.deviceVendor;
      params.deviceNetwork = os.deviceNetwork;
      params.osName = os.osName;
      params.osVendor = os.deviceNetwork;
      params.osVersion = os.osVersion;
      params.osLanguage = window.navigator.language;
    } else {
      params.deviceId = "web";
      params.deviceName = "Web";
      params.deviceVendor = "Web";
      params.deviceNetwork = "Web";
      params.osName = window.navigator.platform;
      params.osVendor = "Web";
      params.osVersion = "";
      params.osLanguage = window.navigator.language;
    }

    if (!params.appName) {
      params.appName = framework.config.info.name;
    }
    if (!params.appVersion) {
      params.appVersion = framework.config.info.version;
    }
    if (!params.appCode) {
      params.appCode = framework.$f7.id || window.qmplus.runtime.appid;
    }
    framework.$f7.request({
      url: framework.config.api.login,
      type: "POST",
      data: params,
      async: async ||true,
      cache: false,
      dataType: "json",
      success: async (result) => {
        if (result && result.success && result.parameters.user) {
          self.setUser(
            result.parameters.user,
            result.parameters.authToken,
            result.parameters.resources || result.parameters.authorities
          );
          vue.$f7.data.currentUser = result.parameters.user;
          vue.$f7.data.authToken = result.parameters.authToken;
          vue.$f7.data.csrfToken = result.parameters.csrfToken;

          if (vue && vue.$store) {
            vue.$store.commit("setModules", result.parameters.modules);
          }
        }

        self
          .getUser()
          .then(() => {
            callback(result);
            if (result && result.success) {
              //fw.security.process();
              if (result.parameters.isForceBind) {
                framework.$f7.router.navigate("/bindDevice/");
              }
              //Run Job
              Object.keys(framework.jobs).forEach((key) => {
                if (framework.jobs[key].anonymous === false) {
                  framework.jobs[key].register();
                }
              });
            }
          })
          .catch((r) => {
            console.log(r);
            framework.util.error(r);
            result.success = false;
            result.message = "获取用户失败";
            callback(result);
          });
      },
      error: (result) => {
        framework.util.error(result);
        result.success = false;
        result.message = "登录失败，请检查网络连接";
        callback(result);
      },
      timeout: (result) => {
        result.success = false;
        result.message = "登录超时";
        callback(result);
      },
    });
  }

  miniLogin(callback) {
    if (window.plus && plus.webview.currentWebview().miniapp && !isLogin) {
      //Miniapp自动登录
      this.login({
          authToken: plus.webview.currentWebview().authToken,
          oauthType: "MINIAPP",
        },
        (r) => {
          if (!r || !r.success) { 
            nextRoute = "/miniapp/noaccess/";
          }
          if (callback) {
            callback(true);
          } else {
            let history = framework.$f7.views.current.router.history;
            if (history && history.length > 0) {
              framework.$f7.views.current.router.history.splice(0, history.length);
            }
            if (nextRoute) {
              framework.$f7.views.current.router.navigate(nextRoute, {
                pushState: false
              });
            } else {
              var viewParams = framework.$f7.router.app.params.view;
              if (viewParams.pushState) {
                var sep = viewParams.pushStateSeparator || "#!";
                var url = window.location.href;
                if (url.indexOf(sep) > -1) {
                  nextRoute = url.substr(url.indexOf(sep) + sep.length);
                  if (framework.$f7.router.findMatchingRoute(Config.pages.login)) {
                    framework.$f7.views.current.router.navigate(nextRoute, {
                      pushState: false
                    });
                    return;
                  }
                }
              }
              framework.redirect.home();
            }
          }
        },
        true
      );
    } else {
      callback(isLogin);
    }
  }

  autoLogin(async) {
    if (token) {
      this.login({
          authToken: token,
          oauthType: "AUTO",
        },
        (result) => {
          if (result && result.success) {
            if (nextRoute) {
              vue.$f7.views.current.router.navigate(nextRoute);
            } else {
              framework.redirect.home();
            }
          } else {
            // 清除token
            vue.$f7.data.authToken = null;
            vue.$f7.data.csrfToken = null;
            this.removeUser();
          }
        },
        async ||false
      );
    }
  }

  ssoLogin(async) {
    this.login({
        oauthType: "SSO",
      },
      (result) => {
        if (result && result.success) {
          homepage = undefined
          framework.redirect.home();
        } else {
          // 清除token
          vue.$f7.data.authToken = null;
          vue.$f7.data.csrfToken = null;
          this.removeUser();
        }
      },
      async ||false
    );
  }

  wechatLogin(params) {
    if (params.accessToken && params.openid) {
      this.login(
        params,
        (result) => {
          if (result && result.success) {
            homepage = undefined
            // if(miniappurl.serverUrl && miniappurl.serverUrl.indexOf('/') !== -1){
            //   vue.$f7.views.current.router.navigate(miniappurl.serverUrl);
            // } else{
            // this.$framework.miniApp.open(miniappurl.serverUrl, null, "white")
            // }
            framework.redirect.home();
          } else {
            // 清除token
            vue.$f7.data.authToken = null;
            vue.$f7.data.csrfToken = null;
            this.removeUser();
            vue.$f7.dialog.alert(result.message || "微信登录失败");
          }
        },
        true
      );
    }
  }

  logout() {
    framework.$f7.dialog.confirm("您确定要退出登录吗？", () => {
      let params = framework.$f7.utils.parseUrlQuery();
      if (
        params &&
        params.type &&
        params.type == "inner" &&
        window.qmplus.isMobile()
      ) {
        framework.viewer.close();
      } else {
        isLogin = false;
        framework.redirect.login();
        this.login({
            oauthType: "LOGOUT",
          },
          () => {
            this.removeUser();
            // 清除token
            vue.$f7.data.authToken = null;
            vue.$f7.data.csrfToken = null;
            homepage = undefined
            // 关闭连接
            window.vue.$disconnect();
          },
          true
        );
      }
    });
  }

  hasPermission(key) {
    if (key && resources && resources.length > 0) {
      let r = resources.some((item) => {
        if (item.role) {
          return item.role.resources.some(res => {
            if (Array.isArray(key)) {
              return res.code && key.includes(res.code.toLowerCase());
            } else {
              return res.code && res.code.toLowerCase() == key.toLowerCase();
            }
          });
        } else if (Array.isArray(key)) {
          return item.code && key.includes(item.code.toLowerCase());
        } else {
          return item.code && item.code.toLowerCase() == key.toLowerCase();
        }
      });
      return r;
    }
    return false;
  }

  hasRole(key) {
    if (key && resources && resources.length > 0) {
      let r = resources.some((item) => {
        if (item.role && item.role.name) {
          if (Array.isArray(key)) {
            return key.includes(item.role.name.toLowerCase());
          } else {
            return item.role.name.toLowerCase() == key.toLowerCase();
          }
        }
        return false;
      });
      return r;
    }
    return false;
  }

  getRsaPublic() {
    return new Promise((resolve, reject) => {
      framework.$f7.request({
        url: framework.config.api.getRsaPublic,
        type: "POST",
        async: false,
        cache: false,
        dataType: "json",
        success: (resp) => {
          const {
            success,
            parameters
          } = resp;
          if (success) {
            resolve(parameters.rsaPublic);
          } else {
            reject();
          }
        },
        error: (err) => {
          framework.$f7.dialog.toast("初始化数据失败！");
          reject();
        },
        timeout: () => {
          framework.$f7.dialog.toast("初始化数据超时！");
          reject();
        },
      });
    });
  }

  /**
   *
   * @param {*} loginId
   * @param {*} password
   * @param {*} rsaPublic
   */
  getLoginEncryptorParam(loginId, password, rsaPublic) {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(rsaPublic);
    return encryptor.encrypt(
      JSON.stringify({
        username: loginId,
        password,
      })
    );
  }
}

export default Account;